package com.twohand.admin.Util;

import com.twohand.utils.Response.BaseException;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@Component
@Data
public class FileUpload {
    String[] imageSuffix = {"png","jpg","gif"};
    Date nowDate = new Date();
    SimpleDateFormat year = new SimpleDateFormat("yyyy");
    SimpleDateFormat month = new SimpleDateFormat("MM");
    String typePath = "images/avatar";
    @Value("${server.servlet.context-path}")
    public String contextPath;
    //文件保存位置
    @Value("${custom.saveStaticPath}")
    public String saveStaticPath;
    //静态访问路径
    @Value("${custom.staticPath}")
    public String staticPath;
    public String uploadImage(MultipartFile multipartFile){
        try {
            if(multipartFile.isEmpty()){
                throw  new BaseException(401,"请选择文件");
            }
            String originalFilename = multipartFile.getOriginalFilename();
            //文件后缀
            String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));

            String basePath = this.getPath(typePath);
            String filename = String.valueOf(UUID.randomUUID()) + fileSuffix;
            //创建文件夹
            File fileExist = new File(basePath);
            if(!fileExist.exists()){
                Boolean mk = fileExist.mkdirs();
            }
            File file = new File(basePath,filename);
            multipartFile.transferTo(file);
            return getSavePath(typePath) +filename;
        }catch (Exception e){
            e.printStackTrace();
            throw new BaseException(500,"文件上传失败,请稍后再试！");
        }
    }
    public String getPath(String type) throws IOException {
        File file = new File(saveStaticPath);
        return file.getCanonicalPath()+this.getSavePath(type);
    }
    public String getSavePath(String type){
        return staticPath+"upload/"+type+"/"+year.format(nowDate)+month.format(nowDate) + "/";
    }
}
